package 所有的题类.ZA.链表;

import com.kiwi.nixu.common.LNode;

import java.util.Arrays;
import java.util.List;

public class 删除链表的倒数第N个结点 {

    public static void main(String[] args) {
        LNode lNode = arrayToLNode(Arrays.asList(1, 2));

        LNode lNode1 = removeNthFromEnd(lNode, 2);
        System.out.println(lNode1.data);
    }
    public static LNode arrayToLNode(List<Integer> list){
        LNode lNode = new LNode(list.get(0));
        LNode cur=lNode;
        for (int i = 1; i < list.size(); i++) {
            LNode tmp=new LNode(list.get(i));
            cur.next=tmp;
            cur=tmp;
        }
        return lNode;
    }


    public static LNode removeNthFromEnd(LNode head, int n) {
        LNode h=head;
        LNode p=head;
        LNode fast=null;
        LNode pre=null;
        LNode slow=head;
        while((n)>0){
            head=head.next;
            n--;
        }
        fast=head;
        if (fast == null) {
            return p.next;
        }
        while(fast!=null){
            fast=fast.next;
            pre=slow;
            slow=slow.next;
        }
        pre.next=pre.next.next;
        return h;
    }
}
